package com.jy.bo.common.conf.util;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.ocr.v20181119.OcrClient;
import com.tencentcloudapi.ocr.v20181119.models.EnglishOCRRequest;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageIdentifyUtils {

    public static String ocrIdentify(String fullUrl) {
        Credential cred = new Credential("AKIDxiCQN3SaR2LN8cpkOlsjKfkY4JHyPYQ1", "MRFmulKdeOs51g4B1Zqqa3F9m9E2YonV");
        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint("ocr.tencentcloudapi.com");
        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);
        OcrClient client = new OcrClient(cred, "ap-hongkong", clientProfile);
        EnglishOCRRequest req = new EnglishOCRRequest();
        req.setImageUrl(fullUrl);

        HashMap<String, String> resMap = new HashMap<>();
        try {
            client.EnglishOCR(req).toMap(resMap, "");
        } catch (TencentCloudSDKException e) {
            e.printStackTrace();
        }
        Iterator<Map.Entry<String, String>> iterator = resMap.entrySet().iterator();

        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            if (entry.getValue().length() == 4) {
                Pattern pattern = Pattern.compile("[0-9]{1,}");
                Matcher matcher = pattern.matcher(entry.getValue());
                boolean result = matcher.matches();
                if (result) {
                    return entry.getValue();
                }
            }
        }

        return "";
    }

}
